﻿<%@ WebHandler Language="C#" Class="sysApplicationHandler" %>

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;

using log4net;
using log4net.Config;

using Web.Library.DomainObject.SQLServer;
using Web.Library.Facade.SQLServer;
using Web.Library.DataAccess.SQLServer;
using Web.Support;

using Web.Support;

public class sysApplicationHandler : BaseHandler {
    private SysApplicationFacade applicationFacade = new SysApplicationFacade(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);


    public override void ProcessRequest(HttpContext context)
    {
        base.ProcessRequest(context);
        context.Response.ContentType = "text/plain";
        string result = Process(context);
        context.Response.Write(result);
    }

    private string Process(HttpContext context)
    {
        string result = string.Empty;
        try
        {
            
            if (context.Request.QueryString["show"] != null)
            {
                //context.Response.Clear();
                //context.Response.Buffer = true;

                //System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

                //string jsonString = string.Empty;
                //jsonString = context.Server.UrlDecode(sr.ReadToEnd());
                //JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

                //sr.Close();
                //sr.Dispose();
                
                switch (context.Request.QueryString["show"].ToString())
                {

                    case "read": result = this.Read(context); break;
                    case "create": result = this.Create(context); break;
                    case "update": result = this.Update(context); break;
                    case "delete": result = this.Delete(context); break;
                }
            }

            
        }
        catch (Exception ex)
        {
            //result = "{success: false, message: 'Error found on page! " + ConfigurationManager.AppSettings["ErrorHelpText"].ToString() + "'}";
            //log.Debug("Process() on GroupHandler.ashx.cs: " + ex.Message.ToString());

            Logger.Debug("Process () sysApplicationHandler.ashx", ex);
        }
        return result;
    }

    private string Delete(HttpContext context)
    {
        string result = string.Empty;
        try
        {
            
            applicationFacade.Delete(Convert.ToInt32(context.Request.QueryString["Id"].ToString()));
            result = "{\"success\": \"true\"}";
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return result;
    }

    private string Update(HttpContext context)
    {
        //string result = string.Empty;
        //JSONHelper helper = new JSONHelper();
        //try
        //{
        //    SysApplication obj = new SysApplication();
        //    obj.AppID = (int)jo["AppID"];
        //    obj.DescApp = (string)jo["DescApp"];
        //    obj.UrlApp = (string)jo["UrlApp"];
        //    obj.UpdatedBy = "BENI";
        //    obj.UpdatedDate = DateTime.Now;
        //    applicationFacade.Update(obj);
        //    //result = "{\"success\": \"true\"}";

        //    helper.Message = "Data berhasil di simpan !";
        //    helper.IsSuccess = true;
        //}
        //catch (Exception ex)
        //{
        //    helper.Message = ex.Message;
        //    helper.IsSuccess = false;
        //    throw ex;
        //}

        //return result;

        JSONHelper helper = new JSONHelper();

        try
        {

            var data = context.Request.Form;
            var txtAppName = context.Server.UrlDecode(data["txtAppName"]);
            var txtAppUrl = context.Server.UrlDecode(data["txtAppUrl"]);
            var txtAppDesc = context.Server.UrlDecode(data["txtAppDesc"]);
            var hfID = context.Server.UrlDecode(data["hfID"]);
            var hfFileName = context.Server.UrlDecode(data["hfFileName"]);

            SysApplication obj = new SysApplication();
            obj.TitleApp = txtAppName;
            obj.DescApp = txtAppDesc;
            obj.UrlApp = txtAppUrl;
            obj.AppID = Convert.ToInt32(hfID);

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];
                string FileName = string.Empty;
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];


                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);



                string namadepartemen = string.Empty;

                string path = string.Empty;
                string ext = string.Empty;


                path = context.Server.MapPath("~/ImageUpload/");
                obj.ImageApp = "ImageUpload/" + hfFileName;// hpf.FileName;

                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);



                if (System.IO.File.Exists(path + hfFileName))
                    System.IO.File.Delete(path + hfFileName);

                hpf.SaveAs(path + hfFileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();
            }

            obj.CreatedDate = DateTime.Now;
            obj.CreatedBy = base.UserLoggedIn;

            //OrganizationalStructureDal.Save(obj);
            if (context.Request.Files.Count > 0)
                applicationFacade.Update(obj);
            else
                applicationFacade.UpdateWithoutImage(obj);
                
            helper.Message = "Data berhasil di simpan !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            //recLog log = new recLog();
            //log.LogEvent = "Insert";
            //log.LogMessage = helper.Message;
            //log.LogSource = "OrganizationalStructurehandler.ashx";
            //log.CreatedBy = base.UserLoggedIn;
            //log.CreatedDate = DateTime.Now;
            //logDal.Save(log);

        }
        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
    }
    
    private string Create(HttpContext context)
    {
        //string result = string.Empty;
        //JSONHelper helper = new JSONHelper();
        //try
        //{
            
        //    SysApplication obj = new SysApplication();
        //    obj.DescApp = (string) jo["DescApp"];
        //    obj.UrlApp = (string) jo["UrlApp"];
        //    obj.CreatedBy = "BENI";
        //    obj.CreatedDate = DateTime.Now;
            
        //    applicationFacade.Save(obj);
            
        //    helper.Message = "Data berhasil di simpan !";
        //    helper.IsSuccess = true;
            
        //}
        //catch (Exception ex)
        //{
        //    //throw ex;
            
        //    helper.Message = ex.Message;
        //    helper.IsSuccess = false;
            
        //}

        ////return result;
        //return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        JSONHelper helper = new JSONHelper();

        try
        {

            var data = context.Request.Form;
            var txtAppName = context.Server.UrlDecode(data["txtAppName"]);
            var txtAppUrl = context.Server.UrlDecode(data["txtAppUrl"]);
            var txtAppDesc = context.Server.UrlDecode(data["txtAppDesc"]);
            var hfID = context.Server.UrlDecode(data["hfID"]);
            var hfFileName = context.Server.UrlDecode(data["hfFileName"]);

            SysApplication obj = new SysApplication();
            obj.TitleApp = txtAppName;
            obj.DescApp = txtAppDesc;
            obj.UrlApp = txtAppUrl;
            
            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];
                string FileName = string.Empty;
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];


                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);



                string namadepartemen = string.Empty;

                string path = string.Empty;
                string ext = string.Empty;
                

                path = context.Server.MapPath("~/ImageUpload/");
                obj.ImageApp = "ImageUpload/" + hfFileName;// hpf.FileName;

                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);



                if (System.IO.File.Exists(path + hfFileName))
                    System.IO.File.Delete(path + hfFileName);

                hpf.SaveAs(path + hfFileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();
            }

            obj.CreatedDate = DateTime.Now;
            obj.CreatedBy = base.UserLoggedIn;

            //OrganizationalStructureDal.Save(obj);

            applicationFacade.Save(obj);
            helper.Message = "Data berhasil di simpan !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            //recLog log = new recLog();
            //log.LogEvent = "Insert";
            //log.LogMessage = helper.Message;
            //log.LogSource = "OrganizationalStructurehandler.ashx";
            //log.CreatedBy = base.UserLoggedIn;
            //log.CreatedDate = DateTime.Now;
            //logDal.Save(log);

        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
    }
    
    private string Read(HttpContext context)
    {
        string result = string.Empty;
        try
        {
            
            string sort = "asc";
            string dir = "AppId";
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);
            int pageSize = 10;
            int.TryParse(context.Request.QueryString["pageSize"] ?? "10", out pageSize);
            SysApplication users = new SysApplication();
            if (context.Request.QueryString["sort[0][dir]"] != null) 
                sort = context.Request.QueryString["sort[0][dir]"].ToString();
            if (context.Request.QueryString["sort[0][field"] != null) 
                dir = context.Request.QueryString["sort[0][field"].ToString();
            //if (context.Request.QueryString["key"] != null) groups.GroupName = context.Request.QueryString["word"].ToString();

            
            List<SysApplication> list = new List<SysApplication>();
            list = applicationFacade.GetList(pageSize, page,dir,sort);
            object countdata = applicationFacade.SelectScalar(Web.Library.Enum.SQL.Function.Aggregate.Count, SysApplication.Fields.AppID);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            result = "{\"pageSize\": " + (int)countdata + ", \"data\": " + serializer.Serialize(list) + "}";

            
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return result;
    }

 
    public bool IsReusable {
        get {
            return false;
        }
    }

}